


// 只有这些充值方式
export const bankPayMethods = [1, 2, 3, 4, 5, 6];
// 充值方式对应的名称
export const bankPayType = [
    { paymenttype: 1, payname: 'bankcard' },
    { paymenttype: 2, payname: 'momo' },
    { paymenttype: 3, payname: 'zalo' },
    { paymenttype: 4, payname: 'viettel' },
    { paymenttype: 5, payname: 'scratchcard' },
    { paymenttype: 6, payname: 'usdt' },
];
export const netWorkArr = [
    { text: 'TRC20', value: 1 },
    { text: 'ERC20', value: 2 },
];



/**
 * @description 转换用户名
 */
export const userNameHiding = (name: string) => {
    if (name) {
        const hiddenChars1 = '**';
        let visibleChars;
        visibleChars = name.slice(0, 2) + hiddenChars1 + name.slice(-2);
        return visibleChars;
    }
}



export const sleep = (time: number) => {
    return new Promise((resolve) => setTimeout(resolve, time));
}

/**
 * 打开外部链接
 * @param val 当前点击项菜单
 */
export const handleOpenLink = (url: string) => {
    let dom = document.createElement('a')
    dom.setAttribute('href', `${url}`)
    dom.setAttribute('target', '_blank')
    document.body.appendChild(dom)
    dom.click()
    document.body.removeChild(dom)
};

/**
 * 小数或整数(不可以负数)
 * @param val 当前值字符串
 * @returns 返回处理后的字符串
 */
export function verifyNumberIntegerAndFloat(val: string) {
    // 匹配空格
    let v = val.replace(/(^\s*)|(\s*$)/g, '');
    // 只能是数字和小数点，不能是其他输入
    v = v.replace(/[^\d.]/g, '');
    // 以0开始只能输入一个
    v = v.replace(/^0{2}$/g, '0');
    // 保证第一位只能是数字，不能是点
    v = v.replace(/^\./g, '');
    // 小数只能出现1位
    v = v.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
    // 小数点后面保留2位
    v = v.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
    // 返回结果
    return v;
}

/**
 * 金额用 `,` 区分开
 * @param val 当前值字符串
 * @returns 返回处理后的字符串
 * isDecimal 是否需要舍弃小数，不需要舍弃 true, 需要舍弃 false
 */
export function verifyNumberComma(val: string, isDecimal: boolean = true) {
    // 调用小数或整数(不可以负数)方法
    let v: any = verifyNumberIntegerAndFloat(val);
    v = isDecimal ? v : Math.trunc(v); // 直接舍弃小数

    // 字符串转成数组
    v = v.toString().split('.');
    // \B 匹配非单词边界，两边都是单词字符或者两边都是非单词字符
    v[0] = v[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    // 数组转字符串
    v = v.join('.');
    // 返回结果
    return v;
}
// 对象转时间显示 dd/MM/yyyy HH:mm:ss
export function convertObjectToDateString(obj: any, origin?: boolean): string {
    let rs = `${padZero(obj.day)}/${padZero(obj.month)}/${obj.year} ${padZero(obj.hour)}:${padZero(obj.minute)}:${padZero(obj.second)}`
    if (origin) {
        rs = `${obj.year}-${padZero(obj.month)}-${padZero(obj.day)} ${padZero(obj.hour)}:${padZero(obj.minute)}:${padZero(obj.second)}`
    }
    return rs == '00/00/00 00:00:00' ? '--' : rs
}
function padZero(n: number): string {
    if (n > 9) return n.toString()
    return '0' + n
}

/**
 * @description 复制
 * @param text
 * @returns
 */
export function copyFn(text: string) {
    var textarea: any = document.createElement('textarea');
    textarea.style.position = 'fixed';
    textarea.style.opacity = 0;
    textarea.value = text;
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand('copy');
    document.body.removeChild(textarea);
}
/**
 *  精确小数点，截取位数，不四舍五入
 *  l 小数点位数
 *  精度丢失问题
 * */
export const toFixedNumber = (value: any, l = 2) => {
    if (!value) {
        return `0.${''.padEnd(l, '0')}`;
    }
    const str = value.toString().split('.');
    const str1 = str[1] ? str[1].substr(0, l).padEnd(l, '0') : ''.padEnd(l, '0');
    return str[0] + '.' + str1;
}

/**
 * 将数字或字符串转换为以 "k" 为单位的格式
 * @param {number | string} input - 需要转换的数字或字符串
 * @returns {string} - 转换后的字符串，带有 "k" 单位
 */
export function formatNumber(input: number | string): string {
    // 将输入转换为浮点数
    let number = parseFloat(input.toString());

    // 如果输入不是有效数字，返回原输入
    if (isNaN(number)) {
        return input.toString();
    }

    // 如果数字小于 1000，直接返回该数字
    if (number < 1000) {
        return number.toString();
    }

    // 将数字转换为以 "k" 为单位的格式，并保留两位小数
    let formattedNumber = (number / 1000).toFixed(2) + 'k';
    return formattedNumber;
}
/**
 * 将数字或字符串转换为以 "k" W 为单位的格式
 * @param {number | string} input - 需要转换的数字或字符串
 * @returns {string} - 转换后的字符串，带有 "k" 单位
 */
export function formatBigNumber(input: number | string) {
    // 将输入转换为浮点数
    let number = parseFloat(input.toString());

    // 如果输入不是有效数字，返回原输入
    if (isNaN(number)) {
        return input.toString();
    }

    // 如果数字小于 10000，直接返回该数字
    if (number < 10000) {
        return number.toString();
    }
    if (number >= 10000 && number < 10000000) {
        return (number / 10000).toFixed(1) + 'W';
    }
    if (number >= 10000000) {
        return (number / 10000000).toFixed(1) + 'KW';
    }
}
/**
 * 将对象数组 按字母顺序排序 
 * @param arr 对象数组；prop：要排序的对象属性key名
 * @returns: nut-elevator list格式
*/
export function sortAndGroupByLetter(arr: any, prop: string) {
    // 按prop属性排序
    const sorted = arr?.sort((a: any, b: any) => a[prop]?.localeCompare(b[prop], 'en'));
    // 根据首字母分组
    const grouped = sorted.reduce((grouped: any, item: any) => {
        const firstChar = item[prop] && item[prop][0]?.toUpperCase() || "*";
        grouped[firstChar] = grouped[firstChar] || [];
        grouped[firstChar].push(item);
        return grouped;
    }, {});
    let list: any = []
    Object.keys(grouped).forEach(key => {
        let item = { title: key, list: <any>[] }
        console.log(key, grouped[key]);
        grouped[key].map((it: any) => {
            item.list.push(it)
        })
        list.push(item)
    })

    // 获取分组的字母数组
    const letters = Object.keys(grouped).sort();

    // 返回分组后的对象，包含字母数组和对应的分组数组
    return { list, letters, grouped };
}
// 去除千位符
export const removeComma = (val: any) => {
    return val ? Number(val.replaceAll(",", "")) : 0;
}
export const handleFocus = () => {
    const bodyElement: any = document.querySelector('body');
    const htmlElement: any = document.querySelector('html');
    bodyElement.style.height = '100%';
    bodyElement.style.overflowY = 'hidden';
    htmlElement.style.height = '100%';
    htmlElement.style.overflowY = 'hidden';
}
export const handleBlur = () => {
    const bodyElement: any = document.querySelector('body');
    const htmlElement: any = document.querySelector('html');
    bodyElement.style.cssText = '';
    htmlElement.style.cssText = '';
}
export const getBlientType = () => {
    // export enum ClientType {
    //     PCWeb = 1,
    //     MobileWeb,
    //     Android,
    //     IOS
    // }
    // 后期判断使用
}
// 用于游戏数据分割成有分页的效果
export const splitArrayIntoChunks = (array: any, chunkSize: number) => {
    let result = [];
    for (let i = 0; i < array.length; i += chunkSize) {
        result.push(array.slice(i, i + chunkSize));
    }
    return result;
}
// 银行卡，显示前4位和后4位, 银行卡最少6位
export const maskTxtString = (str: any, firstNum: number = 4) => {
    if (str?.length <= 8) {
        return str?.substr(0, 4) + " **** **** ";
    }
    return str?.substr(0, firstNum) + " **** **** " + str?.substr(-4);
}
// usdt 地址
export const validateCryptoAddress = (address: any, type: any) => {
    // const regex_1 = /^(1|3|bc1)[a-zA-Z0-9]{25,39}$/; // BTC
    const regex_2 = /^0x[a-fA-F0-9]{40}$/; // ETH, ERC20
    // const regex_3 = /^(L|M|3)[a-zA-Z0-9]{25,33}$/; // LTC
    // const regex_4 = /^r[a-zA-Z0-9]{24,34}$/; // XRP
    // const regex_5 = /^(D|9)[a-zA-Z0-9]{33}$/; // DOGE
    const regex_6 = /^T[a-zA-Z0-9]{33}$/; // TRC20
    const check: any = {
        1: regex_6,
        2: regex_2,
    }
    return check[type].test(address);
}



export const getDeviceType = () => {
    const userAgent = navigator.userAgent || navigator.vendor;

    if (userAgent.match(/iPad/i) || userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
        return 'iOS'; // iOS device
    } else if (userAgent.match(/Android/i)) {
        return 'Android'; // Android device
    } else {
        return 'unknown'; // 其他设备
    }
}
// 设备环境判断 isIosWKWebView isAndroidApp
export const isIosWKWebView = () => {
    const userAgent = navigator.userAgent.toLowerCase();
    const isIOS = /iphone|ipad|ipod/.test(userAgent);
    const isWKWebView = (window as any).webkit && (window as any).webkit.messageHandlers;
    const isNotInBrowser = !/safari|chrome|crios|fxios|edgios|firefox|opera/.test(userAgent);
    return isIOS && isWKWebView && isNotInBrowser;
}
export const isAndroidApp = () => {
    return !!(window as any).AndroidInterface;
}
export const isAppleDevice = () => {
    var userAgent = navigator.userAgent;
    // 检查是否包含 iPhone、iPad 或 iPod
    return /iPhone|iPad|iPod/.test(userAgent);
}
//获取一个格式化的时间
export const getDateFromat = () => {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    const datatime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    return datatime;
};

export const throttleAction = (func: any, limit: any) => {
    let lastFunc: any;
    let lastRan: any;
    return function(this: any, ...args: any) {
        const context = this;
        if (!lastRan) {
            func.apply(context, args);
            lastRan = Date.now();
        } else {
            clearTimeout(lastFunc);
            lastFunc = setTimeout(function() {
                if ((Date.now() - lastRan) >= limit) {
                    func.apply(context, args);
                    lastRan = Date.now();
                }
            }, limit - (Date.now() - lastRan));
        }
    };
}